<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Activity;
use App\Models\UserPrize;
use App\Models\Coupon;
use Carbon\Carbon;
use App\Http\Controllers\Api\V1\Resources\PointsProductResource;
use App\Http\Controllers\Api\V1\Resources\ActivityItemResource;
use Illuminate\Support\Str;

class ActivitiesController extends Controller
{
    
   

    public function index()
    {
        $keyword = request('keyword');
        ActivityItemResource::wrap('data');

        $query = Activity::query();

        
        if($keyword){
            $query = $query->where('title', 'like', "%{$keyword}%");
        }

         $activities = $query->where("acticity_started_at","<=",Carbon::now())->where("acticity_ended_at",">=",Carbon::now())->orderByDesc('id')->paginate();
        
       
        return ActivityItemResource::collection($activities);
    }

    public function homeActivities()
    {
        $keyword = request('keyword');
        ActivityItemResource::wrap('data');

        $query = Activity::query();


         $activities = $query->orderByDesc('id')->take(4)->get();
        
       
        return ActivityItemResource::collection($activities);
    }

    public function show($id)
    {

      $activity = Activity::find($id);
      return new  ActivityItemResource($activity);
    }


    public function prizeTake()
    {

        $activityId = request('activity_id');
        $activity = Activity::find($activityId);

        $user = request()->user();
        $todayPrize = $user->prizes()->whereDate("created_at",Carbon::now())->count();

        if( $activity->acticity_started_at && strtotime($activity->acticity_started_at) > time()){

            fail('活动暂未开始！');
        }

         if( $activity->acticity_ended_at && strtotime($activity->acticity_ended_at) < time()){

            fail('活动已结束！');
        }

        if($todayPrize >= $activity->quantity){

            fail('今日抽奖次数已达上限！');
        }

        if($activity->prizes){

            $prizes =$activity->prizes->toArray();
            $totalProbability = array_sum(array_column($prizes, 'probability'));
    
            $winPrize = "";
            // 生成随机数
            $rand = mt_rand(1, $totalProbability);
            
            // 概率区间计算
            $currentRange = 0;
            foreach ($prizes as $prize) {
                $currentRange += $prize['probability'];
                if ($rand <= $currentRange) {
                    $winPrize = $prize;
                    break;
                }
            }

            if($winPrize){
                $user->prizes()->create([
                   'prize_id'=>$winPrize['id']
                ]);

                if($winPrize['prize_type']=="coupon"){
                    $coupon = Coupon::find($winPrize['coupon_id']);
                    $expiredAt =  $coupon->end_time;
                    $user->couponRecords()->create(["coupon_id"=>$coupon->id,"expired_at"=>$expiredAt]);
                }

            }
            

            return response()->json($winPrize);
        }


    }

    public function prizeRecord()
    {
        $result = UserPrize::query()
                    ->with("user")
                    ->with("prize")
                    ->whereHas('prize', function ($query) {
                        $query->where('prize_type',"!=","notwinning");
                    })
                    ->orderByDesc('id')
                    ->take(20)
                    ->get();
        if($result){
            $result = $result->toArray();

            foreach($result as $k=>$v){
                $result[$k]['coupon_name'] = Coupon::find($v['prize']['coupon_id'])->name;


                $result[$k]['user']['phone'] =  Str::mask($result[$k]['user']['phone'], '*', 3, 4);
            }
        }
        return response()->json($result); 
        
    }
}
